<template>
    <div class="personmessage">
       <v-header title="个人信息" @back="handleNativeBack" :handleClick='true'>
         <p slot="right" @click="handleSubmitUser">保存</p>
       </v-header>

       <scroll :bounce="false" :style="{height: scrollHeight + 'px'}" v-cloak ref="scroll">
           <div class="personMessageWrapper">
             <div class="pictureWrapper">
                  <div class="imageWrapper" :style="{backgroundImage:`url(${user.backgroundImageUrl || myTopImage})`}">
                    <div class="headerImageWrapper" :style="{backgroundImage:`url(${user.headUrl || imageTop})`}">
                    </div>
                    <div class="phoneTopWrapper">
                      <p>{{user.phoneNum}}</p>
                    </div>
                    <div class="dealImageWrapper">
                      <div @click="updateHeader">
                          <button class="btn">修改头像</button>
                      </div>
                        <div @click="updateBackground">
                          <button class="btn">设置背景</button>
                      </div>
                    </div>
                 </div>
             </div>


                <x-input name="username" v-model="user.nickname" placeholder="请输入昵称" class="centerbody nickname">
                  <p slot="label">
                    <font color="red">*</font>昵称</p>
                </x-input>

                <x-input title="姓名" name="username" v-model="user.realName" placeholder="请输入姓名" class="centerbody">
                </x-input>
                <hr class="hrlineOne">
                <div class="sexWrapper">
                  <cell title="性别" v-model="sexSelected" value-align='left' class="centerbody" is-link @click.native="handleSelectedSex" placeholder="请选择">
                  </cell>
                </div>

                <x-input name="email" title="电子邮箱" v-model="user.email" placeholder="请输入邮箱地址" is-type="email" class="centerbody email">
                </x-input>

                <hr class="hrline">
                <div class="calendarWrapper">
                  <datetime  title="生日" v-model="user.birth" class="centerbody birthWrapper" :min-year=1960  clear-text="选择生日"></datetime>
                </div>
                <hr class="hrline">

                <div class="textareaWrapper">
                  <x-textarea  @on-focus="textAreaContent"  title="个性签名" :max="30" class="centerbody textAreaWrapper" v-model="user.signature" placeholder="请输入个性签名"></x-textarea>
                </div>

           </div>
        </scroll>
        <div class="alertWrapper alertWrapperMessage">
            <confirm v-model="showTextArea"
              placeholder="请输入个性签名"
              title="个性签名"
              @on-confirm="onConfirm">
              <x-textarea slot="default" v-model="signatureCopy" style="border: 1px solid #ECECED" :max="30"></x-textarea>
            </confirm>
        </div>

        <cropper v-model="showCropper" :image="cropperImg" @toggle="val => showCropper = val"  @cropperFinish="newHeaderImage"></cropper>
        <input ref="selectImg" type="file" id="change" accept="image" @change="change" style="display: none;"/>

        <actionsheet v-model="showSex" :menus="menusSex" @on-click-menu="clickSex" show-cancel></actionsheet>
    </div>
</template>

<script>
import VHeader from '@/components/v-header/v-header'
import imageTop from '@/assets/img/default_avatar.png'
import { isIOS, isIphoneX } from '@/assets/js/brower'
import Cropper from '@/components/cropper/cropper'
import Scroll from '@/components/scroll/scroll'
import { Cell, CellBox, XInput, Group, Calendar, XTextarea, XButton, Datetime, Confirm, Flexbox, FlexboxItem, Actionsheet } from 'vux'
import { localUser } from '@/assets/js/local'
import axios from '@/api/axiosApi'
import { handleBackMixin } from '@/assets/js/mixin'
import uploadFile from '@/api/uploadFile'
import myTopImage from '@/assets/img/myhome/my_top.png'

export default {
  mixins: [handleBackMixin],
  data () {
    return {
      myTopImage,
      imageTop: imageTop,
      user: {
        headUrl: '',
        sex: 1,
        nickname: '',
        realName: '',
        phoneNum: '',
        email: '',
        birth: '',
        signature: '',
        backgroundImageUrl: ''
      },
      menusSex: {
        boy: '男',
        girl: '女'
      },
      downloadPath: '',
      showTextArea: false,
      signatureCopy: '',
      headerImage: '',
      scrollHeight: '500',
      showCropper: false,
      cropperImg: '',
      showSex: false,
      sexSelected: '请选择',
      allPopupModels: ['showTextArea', 'showCropper', 'showSex']
    }
  },
  methods: {
    handleSubmitUser () {
      let regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
      if (this.user.nickname === '') {
        this.$vux.toast.text('昵称不能为空', 'middle')
        return
      } else if (!regEmail.test(this.user.email) && this.user.email !== '' && this.user.email !== undefined) {
        this.$vux.toast.text('邮箱格式不正确', 'middle')
        return
      }
      let param = {}
      if (this.user.birth === '' || this.user.birth === undefined) {
        param = {
          sex: this.user.sex,
          headUrl: this.user.headUrl,
          nickname: this.user.nickname,
          realName: this.user.realName,
          phoneNum: this.user.phoneNum,
          email: this.user.email,
          signature: this.user.signature,
          backgroundImageUrl: this.user.backgroundImageUrl
        }
      } else {
        param = {
          sex: this.user.sex,
          headUrl: this.user.headUrl,
          nickname: this.user.nickname,
          realName: this.user.realName,
          phoneNum: this.user.phoneNum,
          email: this.user.email,
          birth: this.user.birth,
          signature: this.user.signature,
          backgroundImageUrl: this.user.backgroundImageUrl
        }
      }
      axios.put(this, '/v1/userInfo/' + this.user.id, param, (data) => {
        localUser.set(this.user)
        this.$vux.toast.text('更新个人信息成功', 'middle')
        this.$router.replace('/user')
        /*
        const JIM = this.$store.getters.JIM
        if (JIM) {
          JIM.updateSelfInfo({
            nickname: this.user.nickname
          })
        }
        */
      })
    },
    textAreaContent () {
      if (isIOS()) {
        this.showTextArea = false
      } else {
        this.showTextArea = true
      }
    },
    onCancel () {
    },
    onConfirm () {
      const t = this.signatureCopy
      this.user.signature = t
    },
    updateHeader () {
      this.imageType = 0
      this.selectImg()
    },
    updateBackground () {
      this.imageType = 1
      this.selectImg()
    },
    selectImg () {
      this.$refs.selectImg.dispatchEvent(new MouseEvent('click'))
    },
    change (e) {
      let files = e.target.files || e.dataTransfer.files
      if (!files.length) return
      if (files[0].size === 0) return
      if (this.imageType === 0) {
        // 裁剪头像
        this.cropperImg = files[0]
        this.showCropper = true
      } else {
        // 修改背景
        uploadFile(this, files, (data) => {
          this.user.backgroundImageUrl = data[0].downloadPath
          // localUser.setItem('backgroundImageUrl', data[0].downloadPath)
          // axios.put(this, '/v1/userInfo/' + this.user.id, {backgroundImageUrl: data[0].downloadPath}, (data) => {
          // })
        })
      }
    },
    newHeaderImage (newImg) {
      this.user.headUrl = newImg
      // localUser.setItem('headUrl', newImg)
      // axios.put(this, '/v1/userInfo/' + this.user.id, {headUrl: newImg}, (data) => {
      // })
    },
    // 性别选择
    clickSex (key) {
      if (key === 'boy') {
        this.user.sex = 1
        this.sexSelected = '男'
      } else if (key === 'girl') {
        this.user.sex = 2
        this.sexSelected = '女'
      }
    },
    handleSelectedSex () {
      this.showSex = true
    },
    handleNativeBack () {
      let isUpdate = false
      for (const key in this.user) {
        if (!this.userCopy.hasOwnProperty(key)) {
          isUpdate = true
          break
        }
        if (this.userCopy[key] !== this.user[key]) {
          isUpdate = true
          break
        }
      }
      const _self = this
      if (isUpdate) {
        _self.$vux.confirm.show({
          title: '温馨提示',
          content: '是否放弃修改个人信息',
          onConfirm () {
            _self.$router.go(-1)
          }
        })
      } else {
        _self.$router.go(-1)
      }
      return true
    }
  },
  created () {
    let obj = localUser.get()
    if (obj.sex === '1') {
      this.sexSelected = '男'
    } else if (obj.sex === '2') {
      this.sexSelected = '女'
    }
    if (obj == null) {
      obj = {}
    } else {
      if (obj.signature == null) {
        obj.signature = ''
      }
      // if (obj.backgroundImageUrl == null || obj.backgroundImageUrl === '') {
      //   obj.backgroundImageUrl = myTopImage
      // }
    }
    this.cropperImg = this.user.backgroundImageUrl || this.myTopImage
    this.user = obj
    this.userCopy = Object.assign({}, obj)
    this.signatureCopy = obj.signature
    if (this.user.nickname === '' || this.user.nickname == null) {
      this.user.nickname = '会员' + this.user.phoneNum
    }
  },
  mounted () {
    this.scrollHeight = window.innerHeight - 64
  },
  components: {
    VHeader,
    Cell,
    CellBox,
    imageTop,
    XInput,
    Calendar,
    XTextarea,
    XButton,
    Group,
    Datetime,
    Confirm,
    isIOS,
    isIphoneX,
    Cropper,
    Flexbox,
    FlexboxItem,
    Scroll,
    Actionsheet
  }
}
</script>

<style lang="stylus" scoped>
@import '~@/assets/css/variable.styl'
[v-cloak] {
  display: none;
}
.personmessage {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: $color-background;
  z-index: 101;
  height:100%;
}

.headerimage {
    width:60px;
    height:60px;
}
.imagetext {
    margin-left: 20px;
}

.phone {
    margin-top: 10px;
}

.centerbody {
    background-color:white;
}

.submit  {
    margin-top: 20px
    margin-left: 10%;
    margin-right: 10%;
}

.nickname p{
  margin-right 9px
}

.nickname {
  margin-left -2px
}

.email {
  margin-top 8px
}

.submitButton {
  border-radius:99px;
  border-color: $color-theme;
  color: $color-theme;
  background-color: white;
}


.phoneWrapper {
  background-color white
  margin-top 10px
  height 45px
  line-height 50px
}

.pictureWrapper {
   padding 10px 10px
   background-color white
  .imageWrapper {
      width 100%
      height 200px
      background-size: cover
      background-repeat: no-repeat
      padding-top 30px
      .headerImageWrapper {
        margin:auto
        border-radius: 50%;
        border: 1px solid #d5d5d5;
        width: 100px
        height 100px
        background-size: cover
        background-repeat: no-repeat
      }
      .phoneTopWrapper {
        margin-top 10px
        width 100%
        text-align center
        p {
          color white
          font-size $font-size-desc
        }
      }
      .dealImageWrapper {
        display flex
        justify-content center
        padding-top 13px
        .btn {
            margin-left 15px
            color: white;
            width: 70px;
            height: 33px;
            border: solid 1px white;
            border-radius 3px
            background  transparent
            &:focus {
              outline: none
            }
        }
      }
    }
}
.hrline {
  height:1px;border:none;solid #E4E4E4;
}

.hrlineOne {
  height:1px;border:none;solid #E4E4E4
}

.textareaWrapper {
  margin-top 10px
}
</style>
<style>
.sexWrapper .weui-cell_access .weui-cell__ft {
  color: black;
  padding-left: 16px
}
</style>

